package com.tgy.programmer_code_interview_guide._03_binarytree;

import com.tgy.leetcode.TreeNode;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @Author: tgy
 * @Date: 1/29/21 11:46 AM
 */
public class _02_打印二叉树的边界节点_02 {


    public static void printEdge(TreeNode root) {


        if (root == null) {

            return;
        }

        System.out.println(root.val);

        if (root.left != null && root.right != null) {

            printLeftEdge(root.left,true);
            printRightEdge(root.right,true);

        }else {

            printEdge(root.left != null ? root.left:root.right);
        }
    }

    /**
     * 前序遍历
     * @param node
     * @param isPrint
     */
    private static void printLeftEdge(TreeNode node, boolean isPrint) {

        if (node == null) {
            return;
        }

        if (isPrint || (node.left == null && node.right == null)) {

            System.out.println(node.val);
        }

        printLeftEdge(node.left,isPrint);
        printLeftEdge(node.right,isPrint && node.left == null);
    }

    private static void printRightEdge(TreeNode node, boolean isPrint) {

        if (node == null) {

            return;
        }


        printRightEdge(node.left,isPrint && node.right == null);
        printRightEdge(node.right,isPrint);
        if (isPrint || (node.left == null && node.right == null)) {

            System.out.println(node.val);
        }

    }


    public static void main(String[] args) {

        /**
         *
         *          3
         *        /  \
         *       1    5
         *       \   / \
         *       2  4  6
         *      / \  \
         *    -10 -20 8
         */
        TreeNode root = new  TreeNode(3);

        root.left = new TreeNode(1);
        root.right = new TreeNode(5);
//        root.left.left = new TreeNode(0);
        root.left.right = new TreeNode(2);
        root.left.right.left = new TreeNode(-10);
        root.left.right.right = new TreeNode(-20);
//        root.left.right.right.right = new TreeNode(-30);
//        root.left.right.right.right.left = new TreeNode(-40);

        root.right.left = new TreeNode(4);
        root.right.right = new TreeNode(6);
        root.right.left.right = new TreeNode(8);

        printEdge(root);
    }
}
